#include "errordialogmanager.h"
#include "networkmanager.h"
#include "remotecontrol.h"
#include "wifiscanner.h"
#include "source/logger.h"
#include <QProcess>
#include <QFile>
#include <QTextStream>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QDebug>

RemoteControl::RemoteControl(QObject *parent)
    : QObject(parent)
{

}

void RemoteControl::startupRemoteControl()
{
    LogInfo <<"Attempting to RemoteControl";
    if(updateConfigFile(NetworkManager::instance()->serialnumber()) && startScript())
    {
        ErrorDialogManager::instance().showNonBlockingInfo("打开远程连接成功",
                                                           QString("请联系售后告知其以下信息:\n设备序列号:%1 \n后端IP:%2")
                                                               .arg(NetworkManager::instance()->serialnumber())
                                                               .arg(WiFiScanner::getInstance().ipAddress()));

    }else
    {
        ErrorDialogManager::instance().showNonBlockingError("打开远程连接失败","无法创建密钥文件");
        return;
    }

}

void RemoteControl::stopRemoteControl()
{
    if(stopScript())
    {
        ErrorDialogManager::instance().showNonBlockingInfo("成功关闭远程连接",
                                                           "我们将提供最好的售后服务，有问题请及时联系");

    }else
    {
        ErrorDialogManager::instance().showNonBlockingError("关闭远程连接故障","已经关闭！l");
        return;
    }
}

bool RemoteControl::updateConfigFile(const QString &clientKey)
{
    QFile file(proxyPath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString content;
        QTextStream in(&file);
        while (!in.atEnd()) {
            QString line = in.readLine();
            if (line.startsWith("client.key=")) {
                line = "client.key=" + clientKey;
                qDebug() << "Updating client.key with:" << clientKey;
            }
            content += line + "\n";
        }
        file.close();

        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << content;
            file.close();
            qDebug() << "Config file updated successfully.";
            return true;
        } else {
            qCritical() << "Failed to open config file for writing.";
            return false;
        }
    } else {
        qCritical() << "Failed to open config file for reading.";
        return false;
    }
    return false;
}

bool RemoteControl::startScript()
{
    QStringList arguments; // 如果启动脚本需要传递参数，可以在这里添加
    QString program = proxyStartPath; // 脚本的路径
    qDebug() << "Starting script at:" << proxyStartPath << "with arguments:" << arguments;
    // 使用新的startDetached方法
    if (QProcess::startDetached(program, arguments)) {
        qDebug() << "Startup script executed successfully.";
        return true;
    } else {
        qCritical() << "Failed to execute startup script.";
        return false;
    }
}

bool RemoteControl::stopScript()
{
    QStringList arguments; // 如果启动脚本需要传递参数，可以在这里添加
    QString program = proxyStopPath; // 脚本的路径
    if (QProcess::startDetached(program, arguments)) {
        qDebug() << "Stop script executed successfully.";
        return true;
    } else {
        qCritical() << "Failed to execute stop script.";
        return false;
    }
}
